import logging
import unittest

import requests
from parameterized import parameterized
from bs4 import BeautifulSoup
from api.approve_api import ApproveApi
from api.login_api import LoginApi
from utils import common_assert, read_data, read_html


class TestApproveApi(unittest.TestCase):
    def setUp(self):
        self.session = requests.Session()
        logging.info(F"创建session对象地址{self.session}")
        self.client = ApproveApi(self.session)
        LoginApi(self.session).login_api()

    def tearDown(self):
        self.session.close()
        logging.info(F"session对象{self.session}被关闭")

    @parameterized.expand(read_data("approve_trust_data.json", "approve_api"))
    def test01_approve_api(self, real_name, card_id, expect):
        try:
            resp = self.client.approve_api(real_name, card_id)
            logging.info(f"预取结果: {expect} / 响应结果: {resp.text}")
            common_assert(self, resp, expect)
            self.assertRegex(resp.json()["data"]["card_id"], "^\d{3}\*{4}\d{3}$")
            logging.info("断言通过")
        except Exception as e:
            logging.error(f"断言失败: {e}")
            raise

    @parameterized.expand(read_data("approve_trust_data.json", "get_approve_api"))
    def test02_get_approve_api(self, expect):
        try:
            resp = self.client.get_approve_api()
            logging.info(f"预取响应状态码: {expect['expect_code']} / 响应响应状态码: {resp.status_code}")
            self.assertEqual(expect["expect_code"], resp.status_code)
            self.assertRegex(resp.json()["phone"], expect["expect_phone"])
            logging.info("断言通过")
        except Exception as e:
            logging.error(f"断言失败: {e}")
            raise

    def test03_trust_api(self):
        try:
            resp = self.client.trust_api()
            logging.info(f"响应结果: {resp.text}")
            self.assertEqual(200, resp.status_code)
            self.assertIn("form", resp.text)
            key_value = read_html(resp.json()["description"]["form"], "html.parser", "input")
            resp = self.client.tripartite_trust_api(key_value[0], key_value[1])
            logging.info(f"响应结果: {resp.text}")
            self.assertEqual(200, resp.status_code)
            self.assertIn("OK", resp.text)
            logging.info("断言通过")
        except Exception as e:
            logging.error(f"断言失败: {e}")
            raise
